package com.code.google.wormon;

import java.io.IOException;

import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MetaEventListener;
import javax.sound.midi.MetaMessage;
import javax.sound.midi.MidiChannel;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Receiver;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.sound.midi.Synthesizer;
import javax.sound.midi.Transmitter;
import javax.sound.midi.ShortMessage;


public enum WormonSoundTrack {
	TRACK_1("com/code/google/wormon/resources/lightforce.mid");

	private Sequencer sequencer;
	private int volumeTrack;
	Receiver synthReceiver = null;
	Synthesizer synthesizer  = null;

	WormonSoundTrack(String soundFileName) {
		try {
			Sequence sequence = MidiSystem.getSequence(this.getClass().getClassLoader().getResourceAsStream(soundFileName));

			sequencer = MidiSystem.getSequencer(false);
			sequencer.open();
			sequencer.setSequence(sequence);

			synthesizer = MidiSystem.getSynthesizer();
			synthesizer.open();
			synthReceiver = synthesizer.getReceiver();
			Transmitter seqTransmitter = sequencer.getTransmitter();
			seqTransmitter.setReceiver(synthReceiver);

			sequencer.addMetaEventListener(new MetaEventListener() {
				public void meta(MetaMessage event) {
					if (event.getType() == 47) {
						sequencer.close();
						if (synthesizer != null) {
							synthesizer.close();
						}
					}
				}
			});

			sequencer.setLoopStartPoint(0);
			sequencer.setLoopEndPoint(-1);
			sequencer.setLoopCount(Sequencer.LOOP_CONTINUOUSLY);

		} catch (InvalidMidiDataException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (MidiUnavailableException e) {
			e.printStackTrace();
		} finally {
		}
	}

	public void play(int volume) {
		if (sequencer.isRunning())
			sequencer.stop();
		sequencer.start();
		setVolume(volume);
	}

	public void setVolume( int value ) {
		try {
			volumeTrack = value;
			ShortMessage volumeMessage = new ShortMessage();
			MidiChannel[] channels = synthesizer.getChannels();
			for ( int i = 0; i < channels.length; i++ ) {
				volumeMessage.setMessage( ShortMessage.CONTROL_CHANGE, i, 7, value );
				synthReceiver.send( volumeMessage, -1 );
				//channels[i].controlChange(7, value);
			}
		} catch ( Exception e ) {
			e.printStackTrace();
		}
	}
	
	public int getVolume(){
		return volumeTrack;
	}
}
